﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace XCrawler
{
    /// <summary>
    /// HttpClient 扩展
    /// </summary>
    public static class HttpClientExtensions
    {
        /// <summary>
        /// 只获取相应的头
        /// </summary>
        /// <param name="client"></param>
        /// <param name="requestUri"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> GetResponseHeadersReadAsync(this HttpClient client, string requestUri)
        {
            using (var request = new HttpRequestMessage(HttpMethod.Get, requestUri))
            {
                var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
                return response;
            }
        }

        /// <summary>
        /// 根据响应头获取页面内容数量
        /// </summary>
        /// <param name="client"></param>
        /// <param name="requestUri"></param>
        /// <returns></returns>
        public static async Task<long> GetContentLengthAsync(this HttpClient client, string requestUri)
        {
            var Response = await client.GetResponseHeadersReadAsync(requestUri).ConfigureAwait(false);
            return Response.Content.Headers.ContentLength ?? -1;
        }


        public static async Task<ResponseStreamInfo> GetStreamInfoAsync(this HttpClient client, string requestUri)
        {
            var response = await client.GetAsync(requestUri, HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false);
            return new ResponseStreamInfo(response, await response.EnsureSuccessStatusCode().Content.ReadAsStreamAsync().ConfigureAwait(false),
                response.Content.Headers.ContentLength ?? -1);
        }

     



    }
}
